﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using NetCoreCMS.Web.Areas.WebApi.Models;

namespace NetCoreCMS.Web.Areas.WebApi.Controllers
{
    public class User_RegisterController :  BaseController
    {
        protected Userconfig userConfig;
        protected Sysconfig sysConfig;
        public IUser_groupsService _user_groups { get; set; }
        public IUser_login_logService _user_login_log { get; set; }
        public IUser_point_logService _user_point_log { get; set; }
        public IUser_amount_logService _user_amount_log { get; set; }
        [HttpGet]
        public IActionResult Get(string username, string password, string mobile, string direct,string code)
        {
            userConfig = Common.XMLConfig.Userconfig.loadConfig(_env.ContentRootPath);
            sysConfig = Common.XMLConfig.Sysconfig.loadConfig(_env.ContentRootPath);
            string userip = CMSRequest.GetClientUserIp(HttpContext);
            var duser = _users.GetModel(direct);
            if (duser == null)
            {
                return Ok(new { status = 0, msg = "温馨提示：推荐人不存在！" });
            }
            if (userConfig.passshare == 1 && duser.is_pass == 0)
            {
                return Ok(new { status = 0, msg = "温馨提示：推荐人未激活！" });
            }
            if (duser.is_share == 0 || duser.is_lock == 1)
            {
                return Ok(new { status = 0, msg = "温馨提示：推荐人受限制！" });
            }

            #region 验证各种参数信息
            //检查是否开启会员功能
            if (sysConfig.memberstatus == 0)
            {
                return Ok(new { status = 0, msg = "温馨提示：会员功能已关闭，无法注册！" });
            }
            if (userConfig.regstatus == 0)
            {
                return Ok(new { status = 0, msg = "温馨提示：系统暂不允许注册新用户！" });
            }
            //检查用户输入信息是否为空
            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            {
                return Ok(new { status = 0, msg = "温馨提示：用户名和密码不能为空！" });
            }
            //如果开启手机注册则要验证手机
            if (userConfig.regstatus == 2 && string.IsNullOrEmpty(mobile))
            {
                return Ok(new { status = 0, msg = "温馨提示：手机号码不能为空！" });
            }            
            //检查用户名
            if (_users.Exists(username))
            {
                return Ok(new { status = 0, msg = "温馨提示：该用户名已经存在！" });
            }
            //如果开启手机登录要验证手机
            if (userConfig.mobilelogin == 1 && !string.IsNullOrEmpty(mobile))
            {
                if (_users.ExistsMobile(mobile))
                {
                    return Ok(new { status = 0, msg = "温馨提示：该手机号码已被使用！" });
                }
            }            
            //检查同一IP注册时隔
            if (userConfig.regctrl > 0)
            {
                if (_users.Exists(userip, userConfig.regctrl))
                {
                    return Ok(new { status = 0, msg = "温馨提示：同IP在" + userConfig.regctrl + "小时内禁止重复注册！" });
                }
            }
            //检查默认组别是否存在
            User_groups modelGroup = _user_groups.GetDefault();
            if (modelGroup == null)
            {
                return Ok(new { status = 0, msg = "温馨提示：用户尚未分组，请联系网站管理员！" });
            }
            //检查验证码是否正确
            switch (userConfig.regstatus)
            {
                case 1: //验证网页验证码
                    string result1 = CheckCode.verify_code(code,HttpContext);
                    if (result1 != "success")
                    {
                        return Ok(result1);
                    }
                    break;
                case 2: //验证手机验证码
                    string result2 = CheckCode.verify_sms_code(code, HttpContext);
                    if (result2 != "success")
                    {
                        return Ok(result2);
                    }
                    break;
            }
            #endregion

            #region 保存用户注册信息
            Users model = new Users();
            model.pid = duser.id;
            model.iid = duser.id;
            model.layer = duser.layer + 1;
            model.group_id = modelGroup.id;
            model.user_name = username;
            model.salt = Utils.GetCheckCode(6); //获得6位的salt加密字符串
            model.password = AESEncryptHelper.Encode(password, model.salt);
            model.mobile = mobile;
            model.reg_ip = userip;
            model.reg_time = DateTime.Now;
            //设置用户状态
            if (userConfig.regstatus == 3)
            {
                model.status = 1; //待验证
            }
            else if (userConfig.regverify == 1)
            {
                model.status = 2; //待审核
            }
            else
            {
                model.status = 0; //正常
            }
            //开始写入数据库
            model.id = _users.Add(model);
            if (model.id < 1)
            {
                return Ok(new { status = 0, msg = "温馨提示：请联系网站管理员！" });
            }
            //检查用户组是否需要赠送积分
            if (modelGroup.point > 0)
            {
                _user_point_log.Add(model.id, model.user_name, modelGroup.point, "注册赠送积分", false);
            }
            //检查用户组是否需要赠送金额
            if (modelGroup.amount > 0)
            {
                _user_amount_log.Add(model.id, model.user_name, modelGroup.amount, "注册赠送金额");
            }
            #endregion
            //写入登录日志
            _user_login_log.Add(model.id, model.user_name, "会员登录", CMSRequest.GetClientUserIp(HttpContext));
            #region jwt
            var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Nbf,$"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}") ,
                    new Claim (JwtRegisteredClaimNames.Exp,$"{new DateTimeOffset(DateTime.Now.AddDays(30)).ToUnixTimeSeconds()}"),
                    new Claim(ClaimTypes.Name, username)
                };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: Const.Domain,
                audience: Const.Domain,
                claims: claims,
                expires: DateTime.Now.AddDays(30),
                signingCredentials: creds);

            return Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token)
            });
            #endregion
        }
    }
}